<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--数据-->
            <el-col :span="24" :xs="24">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
                    <el-form-item :label="$locale('teacher.add.Teacher Name')" prop="teacherName">
                        <el-input v-model="queryParams.teacherName" :placeholder="$locale('teacher.add.Please enter the teachers name')" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item :label="$locale('teacher.add.Teachers phone number')" prop="contactMobile">
                        <el-input v-model="queryParams.contactMobile" :placeholder="$locale('teacher.add.Please enter the teachers phone number')" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item :label="$locale('geWudevice.add.state')" prop="status">
                        <el-select v-model="queryParams.status" :placeholder="$locale('geWudevice.add.state')" clearable style="width: 240px">
                            <el-option v-for="dict in dict.type.data_status" :key="dict.value" :label="dict.label" :value="+dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$locale('teacher.add.Teachers email')" prop="contactEmail">
                        <el-input v-model="queryParams.contactEmail" :placeholder="$locale('teacher.add.Please enter the teachers email address')" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $locale('geWudevice.add.search for') }}</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$locale('geWudevice.reset')}}</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" size="mini" @click="handleAdd()">{{ $locale('classList.add.added') }}</el-button>
                        <el-button type="primary" size="mini" @click="handleFreeze()" :disabled="ids.length == 0">{{ $locale('school.add.Batch freeze') }}</el-button>
                        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="openImportTable">{{ $locale('student.import') }}</el-button>
                    </el-col>
                </el-row>

                <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column :label="$locale('teacher.add.teacher')" align="center" key="teacherName" prop="teacherName">
                    </el-table-column>
                    <el-table-column :label="$locale('jobList.add.email')" align="center" key="contactEmail" prop="contactEmail" width="160">
                    </el-table-column>
                    <el-table-column :label="$locale('teacher.add.phone')" align="center" key="contactMobile" prop="contactMobile" width="160">
                    </el-table-column>
                    <el-table-column :label="$locale('myClass.add.School Name')" align="center" key="schoolName" prop="schoolName">
                    </el-table-column>
                    <el-table-column sortable column-key="status" :filters="[{text: $locale('classList.normal'), value: '1'}, {text: $locale('classList.freeze'), value: '0'}]" :filter-method="filterHandler" :label="$locale('geWudevice.add.state')" align="center" key="status" prop="status">
                        <template slot-scope="scope">
                            <el-tag :type="scope.row.status == 0?'success':'danger'" effect="dark">
                                {{ scope.row.status == 0?'正常':'冻结' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$locale('teacher.add.Joined on')" align="center" key="createTime" prop="createTime">
                    </el-table-column>
                    <el-table-column :label="$locale('formMarkering.list.operate')" align="center" width="220" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">{{ $locale('classList.add.modify') }}</el-button>
                            <el-button type="text" size="mini" @click="handleFreeze(scope.row)">{{scope.row.status == 0?$locale('classList.freeze'):$locale('classList.thaw')}}</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
                              {{ $locale('formMarkering.list.delete') }}</el-button>
                            <el-button size="mini" type="text" @click="handleResetting(scope.row)">{{$locale('school.add.Password Reset')}}</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-col>
        </el-row>

        <!-- 添加 -->
        <add ref="add" @getList="getList"></add>
        <import-table :import-url="'/school/teacher/importData'" exportUrl="school/teacher/importTemplate" :exportName="$locale('teacher.add.Teacher data')" ref="import" @ok="getList" />
        <el-dialog :title="$locale('school.add.Password Reset')" :visible.sync="open" width="500px">
            <el-form :model="loginForm" ref="loginForm" size="small" label-width="100px" :rules="rules">
                <el-form-item :label="$locale('myClass.add.Login password')" prop="oldPassword">
                    <el-input v-model="loginForm.oldPassword" :placeholder="$locale('school.add.Set a login password of 6 to 20 digits')" />
                </el-form-item>
                <el-form-item :label="$locale('school.add.Confirm password')" prop="password">
                    <el-input v-model="loginForm.password" :placeholder="$locale('classList.Please enter your login password again')" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{ $locale('school.add.Submit') }}</el-button>
                <el-button @click="open = false">{{ $locale('classList.add.Cancel') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

  <script>
import { deleteById, list, setStatus, setStatusByIds, getExport, importTemplate, resetPwd } from "@/api/myClass/teacher";
import { getClassList } from "@/api/myClass/classList";
import importTable from "@/components/ImportTemplate/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import add from './add/index.vue'
import { getNames } from '@/utils/index'

export default {
    name: "teacher",
    dicts: ['data_status'],
    components: { Treeselect, add, importTable },
    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            teacherList: [],
            // 弹出层标题
            title: "",
            loginForm: {
                id: '',
                password: '',
                oldPassword: ''
            },
            // 部门树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            // 部门名称
            deptName: undefined,
            // 表单参数
            defaultProps: {
                children: "children",
                label: "schoolName"
            },
            // 表单校验
            // 表单校验
            rules: {
                oldPassword: [
                    { required: true, message: this.$locale('classList.Please enter your login password'), trigger: "blur" },
                    { min: 6, max: 20, message: this.$locale('classList.Password length is 6 to 20 digits'), trigger: 'blur' }
                ],
                password: [
                    { required: true, message: this.$locale('classList.Please enter your login password again'), trigger: "blur" },
                    { min: 6, max: 20, message: this.$locale('classList.Password length is 6 to 20 digits'), trigger: 'blur' },
                    { validator: this.validatePasswordConfirm, trigger: 'blur' }
                ]
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                teacherName: '',
                status: '',
                contactEmail: ''
            },
        };
    },
    watch: {
        // 根据名称筛选部门树
        deptName (val) {
            this.$refs.tree.filter(val);
        }
    },
    created () {
        this.getList();
        this.getDeptTree();
    },
    computed: {
        userName () {
            return this.$store.getters.name; // 使用 Vuex 的 getter 获取用户姓名
        }
    },
    methods: {
        /** 查询用户列表 */
        getList () {
            this.loading = true;
            list(this.queryParams).then(({ data }) => {
                this.teacherList = data.records;
                this.total = data.total;
                this.loading = false;
            });
        },
        filterHandler (value, row, column) {
            const property = column['property'];
            return row[property] == value;
        },
        validatePasswordConfirm (rule, value, callback) {
            if (value === '') {
                callback(new Error(this.$locale('classList.Please enter your login password again')));
            } else if (value !== this.loginForm.password) {
                callback(new Error(this.$locale('classList.Entered passwords differ')));
            } else {
                callback();
            }
        },
        /** 查询下拉树结构 */
        getDeptTree () {
            getClassList().then(response => {
                this.deptOptions = response.data;
            });
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.$refs.add.handleAdd()
        },
        /** 冻结按钮操作 */
        handleFreeze (row) {
            const Ids = row && row.id || this.ids;
            this.$modal.confirm(this.$locale('geWudevice.tip4') + getNames(this.teacherList, Ids, 'teacherName') + this.$locale('geWudevice.tip2')).then(() => {
                if (row && row.id) {
                    setStatus({ id: Ids }).then(() => this.getList())
                } else {
                    setStatusByIds({ id: Ids }).then(() => this.getList())
                }
            }).then((res) => {
                if (res.code == 200) this.$modal.msgSuccess(this.$locale('geWudevice.tip5'));
            }).catch(() => { });
        },
        /** 打开导入表弹窗 */
        openImportTable () {
            this.$refs.import.handleImport()
        },
        // 筛选节点
        filterNode (value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick (data) {
            this.queryParams.schoolId = data.id;
            this.handleQuery();
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleBatch () {
            list({ id: this.ids }).then(({ data }) => {
                this.$modal.msgSuccess(this.$locale('jobList.Batch success'));
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["loginForm"].validate(valid => {
                if (valid) {
                    resetPwd(this.loginForm).then(response => {
                        this.$modal.msgSuccess(this.$locale('geWudevice.add.tip5'));
                        this.handleQuery();
                        this.open = false;
                    });
                }
            });
        },

        /** 修改按钮操作 */
        handleUpdate (row) {
            this.$refs.add.handleUpdate(row)
        },
        /** 密码按钮操作 */
        handleResetting (row) {
            this.resetForm("loginForm");
            this.loginForm.id = row.id
            this.open = true
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const Ids = row.id || this.ids;
            this.$modal.confirm(this.$locale('geWudevice.tip1') + getNames(this.teacherList, Ids, 'teacherName') + this.$locale('geWudevice.tip2')).then(function () {
                return deleteById({ id: Ids });
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess(this.$locale('geWudevice.tip3'));
            }).catch(() => { });

        },
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id);
        },
    }
};
  </script>
    <style lang="scss" scoped>
::v-deep .el-table__row--level-1 .el-checkbox {
    display: none;
}
</style>
